import os
import time
from pathlib import Path
from typing import List

from PIL import Image


def list_files_with_pathlib(folder_path: str or Path, recursive: bool = True) -> List[Path]:
    """
    获取指定文件夹下的所有文件。

    :param folder_path: 文件夹路径（字符串或 Path 对象）
    :param recursive: 是否递归遍历子目录，默认为 True
    :return: 包含所有文件 Path 对象的列表
    """
    folder = Path(folder_path)

    if not folder.exists():
        raise FileNotFoundError(f"路径不存在: {folder}")

    if not folder.is_dir():
        raise NotADirectoryError(f"指定的路径不是文件夹: {folder}")

    # 根据是否递归选择方法
    pattern = '**/*' if recursive else '*'

    # 获取所有匹配的项目，并过滤出文件
    files = [item for item in folder.glob(pattern) if item.is_file()]

    return sorted(files)  # 按名称排序返回，便于查看


def get_subfolders(path):
    """获取指定路径下的所有子文件夹"""
    with os.scandir(path) as entries:
        return [entry.name for entry in entries if entry.is_dir()]


def is_folder_empty(path):
    """判断文件夹是否为空"""
    return len(os.listdir(path)) == 0


def delete_empty_folder(folder_path):
    """删除空文件夹"""
    try:
        os.rmdir(folder_path)
        print(f"成功删除空文件夹: {folder_path}")
        return True
    except OSError as e:
        print(f"删除失败: {e}")
        return False


if __name__ == '__main__':
    print('开始')
    timestamp = int(time.time())
    folder_path = "D:\\4\\"
    subfolders = get_subfolders(folder_path)
    for file_1 in subfolders:
        if is_folder_empty(folder_path + file_1):
            print("文件夹为空")
            print(folder_path + file_1)
        else:
            cols = 0
            rows = 0
            output_path = folder_path + file_1 + ".jpg"
            output_path = output_path.replace('\\4\\', '\\2\\')

            aa = folder_path + file_1 + "\\"
            alls_1 = list_files_with_pathlib(aa)
            for all_1 in alls_1:
                file_name = Path(all_1).name
                a1 = int(file_name[0:file_name.index('_')])
                if a1 > cols:
                    cols = a1
                a2 = int(file_name[file_name.index('_') + 1:file_name.index('.')])
                if a2 > rows:
                    rows = a2
            # print(aa)
            # print(cols)
            # print(rows)
            # print(len(alls_1))
            images = [Image.open(img) for img in alls_1]
            # print(len(images))
            # 调整所有图片到相同尺寸(可选)
            widths, heights = zip(*(i.size for i in images))
            max_width = max(widths)
            max_height = max(heights)

            # 计算最终图片尺寸
            total_width = max_width * (cols + 1)
            total_height = max_height * (rows + 1)
            # print("************")
            # print(total_width)
            # print(total_height)
            # print("************")
            new_image = Image.new('RGB', (total_width, total_height), color=(255, 255, 255))
            x_offset, y_offset = 0, 0
            # print("************")
            # print(cols)
            # print(rows)
            # print("************")
            for i, img in enumerate(images):
                # print(str(x_offset)+"  "+str(y_offset))
                lie_1 = int(i / (cols + 1))
                hang_1 = int(i % (cols + 1))
                aaa = aa + str(hang_1) + "_" + str(lie_1) + ".jpg"
                # print(str(hang_1) + "  " + str(lie_1))
                # print(aaa)
                x_offset = max_width * (hang_1)
                y_offset = max_height * (lie_1)
                img_qq = Image.open(aaa)
                new_image.paste(img_qq, (x_offset, y_offset))


            dst = Path(output_path)
            dst.parent.mkdir(parents=True, exist_ok=True)
            new_image.save(output_path)
            # print(f"图片已网格拼接保存至: {output_path}")

            # output_path = folder_path + file_1 + ".jpg"
            # output_path = output_path.replace('\\1\\', '\\2\\')
            # print(aa)

            #
            # cols += 1
            # rows += 1

            # images = [Image.open(img) for img in alls_1]
            # # 找出最大宽高（统一尺寸可选）
            # max_width = max(img.width for img in images)
            # max_height = max(img.height for img in images)
            # total_width = max_width * cols
            # total_height = max_height * rows
            # merged = Image.new('RGB', (total_width, total_height))
            #
            # for hang_1 in range(cols):
            #     for lie_1 in range(rows):
            #         aaa = aa + str(hang_1) + "_" + str(lie_1) + ".jpg"
            #         print(aaa)
            #         img = Image.open(aaa)
            #         x = cols * max_width
            #         y = rows * max_height
            #         x_offset = max_width * (hang_1+1)
            #         y_offset = max_height * (lie_1+1)
            #         print(x_offset)
            #         print(y_offset)
            #         merged.paste(img, (x_offset, y_offset), img)
            # dst = Path(output_path)
            # dst.parent.mkdir(parents=True, exist_ok=True)
            # merged.save(output_path)

    endTime = int(time.time())
    print(str(endTime - timestamp))
    print('结束')
